package com.baidu.calculation_test.ui

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.calculation_test.R
import com.baidu.calculation_test.data.AppDatabase
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class HistoryDialogFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val inflater = LayoutInflater.from(requireContext())
        val view = inflater.inflate(R.layout.dialog_history, null, false)
        val recycler = view.findViewById<RecyclerView>(R.id.recyclerHistory)
        val btnClear = view.findViewById<Button>(R.id.btnClearHistory)
        val adapter = HistoryAdapter()
        recycler.layoutManager = LinearLayoutManager(requireContext())
        recycler.adapter = adapter

        val dao = AppDatabase.get(requireContext()).historyDao()
        lifecycleScope.launch {
            dao.observeAll().collectLatest { list ->
                adapter.submitList(list)
            }
        }

        btnClear.setOnClickListener {
            lifecycleScope.launch {
                dao.clearAll()
            }
        }

        return AlertDialog.Builder(requireContext())
            .setTitle(R.string.history_title)
            .setView(view)
            .setPositiveButton(android.R.string.ok, null)
            .create()
    }
}


